package com.qf.business.user.core.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.business.user.core.dao.WxUserDao;
import com.qf.commons.core.exception.ServiceException;
import com.qf.data.user.entity.WxUser;
import com.qf.business.user.core.service.WxUserService;
import com.qf.data.user.vo.input.WxScoreUpdateInput;
import com.qf.data.user.vo.input.WxUserInput;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

/**
 * 小程序端的用户表(WxUser)表服务实现类
 *
 * @author makejava
 * @since 2022-09-27 09:35:07
 */
@Service("wxUserService")
@Slf4j
public class WxUserServiceImpl extends ServiceImpl<WxUserDao, WxUser> implements WxUserService {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 小程序端登录
     * @param wxUserInput
     * @return
     */
    @Override
    public WxUser login(WxUserInput wxUserInput) {
        //获得前端的code码
        String code = wxUserInput.getCode();
        //发送请求给微信服务器 校验code是否正确 并且获取小程序端的相关参数（openid）
        String response = restTemplate
                .getForObject("https://api.weixin.qq.com/sns/jscode2session?appid=wxdd8409202137787f&secret=25229e73b6e129f7a82a0040fbdacd45&js_code=" + wxUserInput.getCode() + "&grant_type=authorization_code", String.class);
        log.debug("[wx login] 小程序端登录 - {}", response);

        JSONObject jsonObject = JSON.parseObject(response);
        Integer errcode = (Integer) jsonObject.get("errcode");
        if (errcode != null && errcode != 0) {
            throw new ServiceException(500, "小程序端登录异常");
        }

        //解析
        String sessionKey = jsonObject.getString("session_key");
        String openid = jsonObject.getString("openid");

        //根据openid查询数据库 看是否已经存在当前的用户信息
        WxUser wxUser = this.query().eq("openid", openid).one();
        if (wxUser == null) {
            //没有用户信息 ， 就需要自动保存
            wxUser = new WxUser()
                    .setOpenid(openid)
                    .setSessionKey(sessionKey)
                    .setHeader(wxUserInput.getHeader())
                    .setNickname(wxUserInput.getNickname());
            //保存用户信息
            this.save(wxUser);
        }

        return wxUser;
    }

    @Override
    @Transactional
    public int updateWxScore(WxScoreUpdateInput scoreUpdateInput) {
        return getBaseMapper().updateWxScore(scoreUpdateInput);
    }
}

